#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : #time#
# @Author  : Tuut
# @Email   : 49616026@qq.com
# @File    : #serviceName#.py
import time
from bean.#beanName# import #beanName#
from conn.MyLogs import MyLogs

suffix = time.strftime("%Y%m%d", time.localtime())


class #serviceName#:

    rds_conn = {}
    conn = {}

    def __init__(self, redis_conn, mysql_conn):
        self.rds_conn = redis_conn
        self.conn = mysql_conn

    def fetch_with_param(self, param):
        result = []
        try:
            int_begin = 0
            if param['pageNum'] > 1:
                int_begin = (param['pageNum'] - 1) * param['pageSize']
            elif param['pageNum'] == 1:
                int_begin = 0 * param['pageSize']

            count_sql = f"SELECT COUNT(1) FROM {str(#beanName#.TABLE_NAME).lower()}"
            _total = self.conn.sql_execute(count_sql)
            data_total = _total[0][0]
            fetch_sql = f"SELECT {#beanName#.to_string(False)} FROM `{str(#beanName#.TABLE_NAME).lower()}` WHERE 1=1 AND {#beanName#.split_params(param)}"
            order_sql = f" ORDER BY `sort_key` ASC, `id` DESC"
            limit_sql = f" LIMIT {int_begin}, {param['pageSize']} "
            fetch_sql = fetch_sql + order_sql + limit_sql
            data_list = self.conn.sql_execute(fetch_sql)
            if len(data_list) > 0:
                for in_data in data_list:
                    result.append(#beanName#.chg_data_2_dict(False, in_data))
            return {"code": 200, "data": result, "total": data_total}
        except Exception as e:
            MyLogs.logger.error("ERROR: %s" % e)
        return {"code": 500, "data": None}

    def fetch_with_sno(self, _sno):
        result = []
        try:
            fetch_sql = f"SELECT {#beanName#.to_string(False)} FROM `{str(#beanName#.TABLE_NAME).lower()}` " \
                        f"WHERE 1=1 AND `sno` = \'{_sno}\'"
            data_list = self.conn.sql_execute(fetch_sql)
            if len(data_list) > 0:
                for in_data in data_list:
                    result.append(#beanName#.chg_data_2_dict(False, in_data))
                return {"code": 200, "data": result, 'message': ""}
            else:
                return {"code": 404, "data": result, 'message': '未找到关系数据'}
        except Exception as e:
            MyLogs.logger.error("ERROR: %s" % e)
        return {"code": 500, "data": None}

    def info(self, input_id):
        try:
            fetch_sql = f"SELECT {#beanName#.to_string(False)} FROM `{str(#beanName#.TABLE_NAME).lower()}` " \
                        f"WHERE 1=1 AND `id` = {int(input_id)}"
            data_list = self.conn.sql_execute(fetch_sql)
            if len(data_list) > 0:
                res = #beanName#.chg_data_2_dict(False, data_list[0])
            return {"code": 200, "data": res}
        except Exception as e:
            MyLogs.logger.error("ERROR: %s" % e)
        return {"code": 500, "data": None}

    def add(self, data):
        try:
            insert_sql = f" INSERT INTO `{str(#beanName#.TABLE_NAME).lower()}` ( {#beanName#.split_data_clum(False)} ) " \
                         f" VALUES %s " % "(" + #beanName#.chg_dict_2_data(False, data) + ")"
            self.conn.sql_commit(insert_sql)
            return {"code": 200, "data": None}
        except Exception as e:
            MyLogs.logger.error("ERROR: %s" % e)
        return {"code": 500, "data": None}

    def update(self, input_id, data):
        try:
            update_str = #beanName#.split_params(data)
            update_sql = f"UPDATE `{str(#beanName#.TABLE_NAME).lower()}` SET %s WHERE id = %d" % (update_str, input_id)
            self.conn.sql_commit(update_sql)
            return {"code": 200, "data": [], "pages": 1, "total": 0}
        except Exception as e:
            MyLogs.logger.error("ERROR: %s" % e)
        return {"code": 500, "data": None}

    def delete(self, input_id):
        try:
            fetch_data_sql = f"SELECT `id` FROM {str(#beanName#.TABLE_NAME).lower()} WHERE `id` = %d" % int(input_id)
            one_data = self.conn.sql_execute(fetch_data_sql)
            if len(one_data) > 0:
                delete_sql = f"DELETE FROM `{str(#beanName#.TABLE_NAME).lower()}` WHERE `id` = %d" % int(input_id)
            self.conn.sql_commit(delete_sql)
            return {"code": 200, "data": [], "pages": 1, "total": 0}
        except Exception as e:
            MyLogs.logger.error("ERROR: %s" % e)
            return {"code": 500, "data": None}

    def setAct(self, input_id, act_flg):
        try:
            fetch_data_sql = f"SELECT `id` FROM {str(#beanName#.TABLE_NAME).lower()} WHERE `id` = %d" % int(input_id)
            one_data = self.conn.sql_execute(fetch_data_sql)
            if len(one_data) > 0:
                act_sql = f"UPDATE `{str(#beanName#.TABLE_NAME).lower()}` SET `view_key` = {act_flg} WHERE `id` = %d" % int(input_id)
            self.conn.sql_commit(act_sql)
            return {"code": 200, "data": [], "pages": 1, "total": 0}
        except Exception as e:
            MyLogs.logger.error("ERROR: %s" % e)
            return {"code": 500, "data": None}
